const Router = require('koa-router')
const { User, RegCode } = require('../db')
const emailInterceptor = require('../intercepror/email')
const log4js = require('../config/log4js')
const log = log4js.getLogger()
const fs = require('fs')
const userC = require('../controller/user')
const userI = require('../intercepror/user')

const route = new Router({
  prefix: '/user'
})

route
  .get('/email/verify', emailInterceptor.verifyEmailToken,
    async ctx => {
      log.info(ctx.tl)
      await User.findByIdAndUpdate(ctx.tl._id, {
        state: 0
      })
      ctx.body = 'success'
    })

  .post('/avatar', async ctx => {
    await User.findByIdAndUpdate(ctx.user.id, {
      avatar: fs.readFileSync(ctx.request.files.avatar.path)
    })
    ctx.body = 'success'
  })

  .get('/', async ctx => {
    const user = await User.findById(ctx.user.id)
    ctx.body = user
  })

  .post('/password', userI.verifyOldPassword, userC.updatePassword)

  .post('/regCode', userI.emailVerified, async ctx => {
    const { expireIn } = ctx.request.body
    const regCode = new RegCode({
      fromUser: ctx.user.id,
      fromUsername: ctx.user.username,
      expireTime: Date.now() + (expireIn > 30 ? 30 : expireIn) * 24 * 60 * 60 * 1000
    })

    ctx.body = await regCode.save()
  })

  .get('/regCode', async ctx => {
    const regCodes = await RegCode.find({
      fromUser: ctx.user.id
    }).sort({
      expireTime: 1
    })
    ctx.body = regCodes
  })

  .delete('/regCode', async ctx => {
    const regCode = await RegCode.findById(ctx.request.body.id)
    if (regCode && regCode.useTime < Date.now() && new Date(regCode.useTime).getMilliseconds() !== 0) {
      ctx.throw('已使用的码不能删除')
    } else {
      ctx.body = await regCode.remove()
    }
  })

module.exports = route
